package com.amigo.online.provider.video.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.amigo.online.provider.video.rocketmq.config.RocketMqProperties;
import com.amigo.online.provider.video.rocketmq.model.BaseMqSendModel;


@Service
@Slf4j
public class RocketMqUtil implements ApplicationContextAware {


    private static ApplicationContext context;

    public static SendResult send(BaseMqSendModel baseMqSendModel) {
        SendResult r = null;
        try {
            DefaultMQProducer producer = (DefaultMQProducer) context.getBean(RocketMqProperties.DEFAULT);
            producer.setVipChannelEnabled(false);
            RocketMqProperties rocketMqProperties = (RocketMqProperties) context.getBean(RocketMqProperties.class);
            Message msg = new Message(rocketMqProperties.getDefaultTopic(), baseMqSendModel.getTag(), getRandomKey(),
                    JSON.toJSONBytes(baseMqSendModel));
            r = producer.send(msg, 2000);
            log.info("消息发送成功!发送的消息为:" +  JSON.toJSONString(baseMqSendModel));
        } catch (Exception e) {
            log.error("消息发送失败!发送的消息为:" + baseMqSendModel.toString(), e);
        }
        return r;
    }

    private static String getRandomKey() {
        RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('a', 'z').build();
        return generator.generate(10);
    }

    public DefaultMQProducer getDefaultMQProducer() {
        return (DefaultMQProducer) context.getBean(RocketMqProperties.DEFAULT);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;

    }

    /**
     * RocketMQ 消息发送方法
     *
     * @param
     * @param object
     * @param tag
     * @return
     */
    public static SendResult send(String beanName, Object object, String tag) {
        BaseMqSendModel baseMqSendModel = new BaseMqSendModel();
        baseMqSendModel.setSendContentBean(object);
        baseMqSendModel.setTag(tag);
        baseMqSendModel.setBeanName(beanName);
        return send(baseMqSendModel);
    }

}
